package com.opdar.athena.client.agent.registry;

import com.opdar.athena.client.agent.base.Configuration;
import com.opdar.athena.registry.Registry;
import com.opdar.athena.registry.ZookeeperRegistry;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by shiju on 2017/7/2.
 */
public class ClientAgentRegistry extends ZookeeperRegistry implements Registry {
    Logger logger = LoggerFactory.getLogger(getClass());
    String path;
    public ClientAgentRegistry(String host) {
        super(host);
    }

    public ClientAgentRegistry(String module, String host) {
        super(module, host);
    }

    @Override
    public boolean regist() {
        read();
        String host = bindAddress();
        path = host + ":" + Configuration.getConfiguration().getPort();
        Configuration.getConfiguration().setLocalAddress(new InetSocketAddress(host,Configuration.getConfiguration().getPort()));
        String project = Configuration.getConfiguration().getProject();
        Integer version = Configuration.getConfiguration().getVersion();
        ByteArrayOutputStream byteArrayOutputStream = null;
        DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream = new ByteArrayOutputStream());
        try {
            dataOutputStream.writeUTF(project);
            dataOutputStream.writeInt(version);
        } catch (IOException e) {
            e.printStackTrace();
        }
        final byte[] configData = byteArrayOutputStream.toByteArray();
        add(path,configData);

        try {
            exists(path, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getType() == Event.EventType.NodeDeleted){
                        add(path,configData);
                    }
                }
            });
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getAddresses().size() > 0;
    }
}
